package com.lagou.edu.service.impl;

import com.lagou.edu.entity.LagouAuthCode;
import com.lagou.edu.mapper.LagouAuthCodeMapper;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class CodeServiceLmpl implements CodeService {
    @Reference(timeout = 8000)
    private EmailService emailService;

    @Autowired
    LagouAuthCodeMapper lagouAuthCodeMapper;
    @Override
    public boolean sendCodeToEmail(String email) {
        Boolean result = false;
        //随机生成6位数的数字
        int code=(int)((Math.random() * 9 + 1) * 100000);
        String codeStr= String.valueOf(code);
        String format = "YYYY-MM-dd hh:mm:ss";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
        String expireTime = LocalDateTime.now().plusMinutes(10).format(DateTimeFormatter.ofPattern(format));

        LagouAuthCode lagouAuthCode = LagouAuthCode.builder().email(email).
                code(codeStr).createTime(createTime).expireTime(expireTime).build();

        Integer integer = lagouAuthCodeMapper.insertCode(lagouAuthCode);
        if (integer>0){
            // /email/{email}/{code}
            result = emailService.sendEmail(email, codeStr);
        }
        return result;
    }
}
